#include "Coordinate.h"
Coordinate::Coordinate(uint32 x,uint32 y)
:Component("Coordinate"),
m_screenWidth(x),
m_screenHeight(y)
{
    m_hscreenWidth=x/2;
    m_hscreenHeight=y/2;
}

Coordinate::~Coordinate(void)
{
}



void Coordinate::addedToObject()
{
}

Coordinate*	Coordinate::Instance(uint32 x,uint32 y)
{
    static Coordinate instance(x,y);
    return &instance;
}

Ray* Coordinate::ScreenToWorldCoord(D3DXVECTOR2* p)
{
    CAMERA_INFO cif;
    sendMessage("GetCameraInfo",&cif);
    float dx=(p->x/(float)m_hscreenWidth-1.0f)*cif.m_aspect;
    float dy=(1.0f-p->y/m_hscreenHeight);
    float tmp=tanf(cif.m_fovy/2);

    D3DXMATRIX invMatrix;
    D3DXMatrixInverse(&invMatrix,NULL,&cif.m_ViewMatrix);
    D3DXVECTOR3 p1=D3DXVECTOR3(dx*cif.m_zn*tmp,dy*cif.m_zn*tmp,cif.m_zn);
    D3DXVECTOR3 p2=D3DXVECTOR3(dx*cif.m_zf*tmp,dy*cif.m_zf*tmp,cif.m_zf);
    D3DXVec3TransformCoord(&p1,&p1,&invMatrix);
    D3DXVec3TransformCoord(&p2,&p2,&invMatrix);
    return new Ray(p1,p2-p1);
}

D3DXVECTOR2 Coordinate::WorldToScreenCoord(D3DXVECTOR3* pos)
{
    CAMERA_INFO cif;
    sendMessage("GetCameraInfo",&cif);
    D3DXVECTOR3 tmp;
    D3DXVec3TransformCoord(&tmp,pos,&cif.m_ViewMatrix);
    float tf=tanf(cif.m_fovy/2);
    if(tmp.z<1)
        tmp.z=1;
    float dx=tmp.x/(tf*tmp.z);
    float dy=tmp.y/(tf*tmp.z);
    float x=(dx/cif.m_aspect+1.0f)*(float)m_screenWidth/2.0f;
    float y=(1.0f-dy)*(float)m_screenHeight/2.0f;
    return D3DXVECTOR2(x,y);
}